#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append(r'TQPY\\')
from  tq_py.strategy import Strategy
from tq_py.config import Config
import copy
import time
import decimal
import pandas as pd
from tqsdk import TqApi, TqAuth, TargetPosTask,TqKq
import pandas as pd
import numpy as np
from datetime import datetime
import yaml
from tqsdk.ta import BOLL
import talib as ta
class bandadx5min(Strategy):
    def __init__(self,dict_cfg):
        super().__init__(dict_cfg)
        self.n=60
        self.loss_n=2
        self.r=0.3#band 的比例

        dict_cfg=self.load_config(self.configfile)
        self.sub_params = dict_cfg['Params']
        self.buy_entryprice=self.sub_params['buy_entryprice']
        self.sellshort_entryprice=self.sub_params['sellshort_entryprice']
        self.buy_after_highest=self.sub_params['buy_after_highest']#买入后的最高价格
        self.sellshort_after_lowest=self.sub_params['sellshort_after_lowest']#卖出后的最低价格
        self.band_flag = self.sub_params['band_flag']
        self.upband=self.sub_params['upband']
        self.downband=self.sub_params['downband']


    def stra(self):


        while True:
            self.api.wait_update()
            # 每次生成新的K线时重新计算指标
            #print(self.stra_name)
            if self.api.is_changing(self.klines.iloc[-1], "datetime"):

                self.ma5 = ta.SMA(self.klines.close.astype('float64'), 5)
                self.ma40 = ta.SMA(self.klines.close.astype('float64'), 40)
                self.ma100 = ta.SMA(self.klines.close.astype('float64'), 100)
                self.long_flag = (self.ma40 > self.ma100)
                self.short_flag = (self.ma40 < self.ma100)
                self.adx = ta.ADX(self.klines.high.astype('float64'), self.klines.low.astype('float64'), self.klines.close.astype('float64'),
                                  timeperiod=14)


                if self.band_flag == True:
                    self.upband = float(self.klines['high'].values[-(self.n+1):-1].max())
                    self.downband = float(self.klines['low'].values[-(self.n+1):-1].min())
                    self.band_flag = False

                    params = self.load_config(self.configfile)
                    params['Params']['upband'] = self.upband
                    params['Params']['downband'] = self.downband
                    params['Params']['band_flag'] = self.band_flag
                    self.dump_config(self.configfile, params)

                band = (self.upband - self.downband)
                stoploss = self.r * band
                adx = self.adx[:-1]
                adx_percentage10 = 0.2 * (np.nanmax(adx) - np.nanmin(adx)) + np.nanmin(adx)
                adx_percentage90 = 0.1 * (np.nanmax(adx) - np.nanmin(adx)) + np.nanmin(adx)

                if self.adx.iloc[-1] > adx_percentage90:
                    # if self.atr[i]>atr_percentage90:
                    if self.ma5.iloc[-2] <= self.upband and self.ma5.iloc[-1] > self.upband and self.MarketPosition != 1:
                        self.buy()
                        self.buy_entryprice = float(self.klines.close.iloc[-1])
                        self.buy_after_highest = float(self.klines.high.iloc[-1])

                        params = self.load_config(self.configfile)
                        params['Params']['buy_entryprice'] = self.buy_entryprice
                        params['Params']['buy_after_highest'] = self.buy_after_highest
                        self.dump_config(self.configfile, params)

                    if self.ma5.iloc[-2] >= self.downband and self.ma5.iloc[-1] < self.downband and self.MarketPosition != -1:
                        self.sellshort()
                        self.sellshort_entryprice = float(self.klines.close.iloc[-1])
                        self.sellshort_after_lowest = float(self.klines.low.iloc[-1])

                        params = self.load_config(self.configfile)
                        params['Params']['sellshort_entryprice'] = self.sellshort_entryprice
                        params['Params']['sellshort_after_lowest'] = self.sellshort_after_lowest
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == -1:

                    if self.klines.low.iloc[-1] < self.sellshort_after_lowest:
                        self.sellshort_after_lowest = float(self.klines.low.iloc[-1])

                        params = self.load_config(self.configfile)
                        params['Params']['sellshort_after_lowest'] = self.sellshort_after_lowest
                        self.dump_config(self.configfile, params)
                    if self.klines.high.iloc[-1] - self.sellshort_entryprice >= stoploss:
                        self.buytocover()
                        self.band_flag = True

                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == 1:

                    if self.klines.high.iloc[-1] > self.buy_after_highest:
                        self.buy_after_highest = float(self.klines.high.iloc[-1])

                        params = self.load_config(self.configfile)
                        params['Params']['buy_after_highest'] = self.buy_after_highest
                        self.dump_config(self.configfile, params)
                    if self.buy_entryprice - self.klines.low.iloc[-1] > stoploss:
                        self.sell()
                        self.band_flag = True

                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == 1 and self.klines.close.iloc[-1] - self.buy_entryprice > 0:

                    if self.ma40.iloc[-1] < self.ma100.iloc[-1] and self.klines.close.iloc[-1] < self.klines['low'].values[-(self.loss_n+1):-1].min():
                        self.sell()
                        self.band_flag = True
                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == -1 and self.sellshort_entryprice - self.klines.close.iloc[-1] > 0:
                    if self.ma40.iloc[-1] > self.ma100.iloc[-1] and self.klines.close.iloc[-1] > self.klines['high'].values[-(self.loss_n+1):-1].max():
                        self.buytocover()
                        self.band_flag = True
                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == 1:
                    if self.buy_after_highest > self.upband + 4 * self.r * band and self.klines.close.iloc[-1] < self.upband + 1 * self.r * band and self.klines.close.iloc[-2] > self.upband + 1 * self.r * band:
                        self.sell()
                        self.band_flag = True
                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)

                if self.MarketPosition == -1:
                    if self.sellshort_after_lowest < self.downband - 4 * self.r * band and self.klines.close.iloc[-1] > self.downband - 1 * self.r * band and self.klines.close.iloc[-2] < self.downband - 1 * self.r * band:
                        self.buytocover()
                        self.band_flag = True
                        params = self.load_config(self.configfile)
                        params['Params']['band_flag'] = self.band_flag
                        self.dump_config(self.configfile, params)



        self.api.close()


